import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// import 'package:flutter_email_sender/flutter_email_sender.dart';

class EmailSender extends StatefulWidget {
  const EmailSender({Key? key}) : super(key: key);

  @override
  State<EmailSender> createState() => _EmailSenderState();
}

class _EmailSenderState extends State<EmailSender> {
  final Key formKey = GlobalKey<FormState>();

  TextEditingController recieverController = TextEditingController();
  TextEditingController subjectController = TextEditingController();
  TextEditingController bodyController = TextEditingController();

  // 邮件发送
  void sendEmail(String recipent, String subject, String body) async {
    // final Email email = Email(
    //   body: body,
    //   subject: subject,
    //   recipients: [recipent],
    //   // cc: ['cc@example.com'],
    //   // bcc: ['bcc@example.com'],
    //   // attachmentPaths: ['/path/to/attachment.zip'],
    //   isHTML: false,
    // );

    // await FlutterEmailSender.send(email);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('邮件发送器'),
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Form(
            key: formKey,
            child: Column(children: [
              TextField(
                controller: recieverController,
                inputFormatters: [
                  EmailInputFormatter()
                ],
                decoration: const InputDecoration(
                  hintText: '收件人',
                ),
              ),
              TextField(
                controller: subjectController,
                decoration: const InputDecoration(
                  hintText: '主题',
                ),
              ),
              TextField(
                controller: bodyController,
                decoration: const InputDecoration(
                  hintText: '内容',
                ),
              ),
              ElevatedButton(
                child: const Text('发送'),
                onPressed: (){
                  sendEmail(
                    recieverController.text, 
                    subjectController.text, 
                    bodyController.text
                  );
                }
              )
            ]),
          ),
        )
      )
    );
  }
}

class EmailInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    // 获取新的输入值
    String newText = newValue.text;

    // 检查新的输入值是否符合电子邮件格式
    if (newText.isNotEmpty && !RegExp(r'^[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]*\.[a-zA-Z]{2,}$').hasMatch(newText)) {
      // 如果不符合格式，恢复旧值
      return oldValue;
    }

    // 如果符合格式，允许更新
    return newValue;
  }
}